package wnhz.com.business.rebateshop.activity.mine;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import wnhz.com.business.R;
import wnhz.com.business.groupshop.adapter.FragmentAllAdapter;
import wnhz.com.business.base.BaseFragment;
import wnhz.com.business.base.BaseRecyclerAdapter;
import wnhz.com.business.groupshop.bean.OrderBean;
import wnhz.com.business.groupshop.ui.EvaluateActivity;
import wnhz.com.business.groupshop.ui.LogisticsActivity;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.uitls.decoration.HorizDecoration;
import wnhz.com.business.uitls.dialog.SimpleDialog;

import static android.app.Activity.RESULT_OK;

public class OrderAllFragment extends BaseFragment implements BaseRecyclerAdapter.OnDataLoadFinish {

    @BindView(R.id.recycler_View)
    RecyclerView recyclerView;
    @BindView(R.id.empty_layout)
    LinearLayout layEmtpy;
    @BindView(R.id.tv_msg)
    TextView tv_msg;

    private FragmentAllAdapter fragmentAllAdapter;
    private List<OrderBean.InfoBean> orderInfos = new ArrayList<>();
    private AllOrderActivity activity;
    private SimpleDialog simpleDialog;

    private final int REQUEST_EVALUATE = 222;

    public static OrderAllFragment getInstance() {
        OrderAllFragment sf = new OrderAllFragment();
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootview = inflater.inflate(R.layout.order_one_fragment, null);
        ButterKnife.bind(this, rootview);
        activity = (AllOrderActivity) getActivity();
        initView();
        return rootview;
    }

    private void initView() {
        fragmentAllAdapter = new FragmentAllAdapter(activity, orderInfos);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new HorizDecoration(20));
        fragmentAllAdapter.setOnDataLoadFinish(this);
        fragmentAllAdapter.loadDataFirstTime();
        recyclerView.setAdapter(fragmentAllAdapter);

        fragmentAllAdapter.setOnClickListener(new FragmentAllAdapter.MyItemClickLinstener() {
            @Override
            public void OnCancleClickListener(final FragmentAllAdapter adapter, final int position, View view) {
                simpleDialog = new SimpleDialog(getContext(), "取消订单, 交易将关闭!", "再想想", "确定", new SimpleDialog.OnButtonClick() {
                    @Override
                    public void onNegBtnClick() {
                        simpleDialog.cancel();
                    }

                    @Override
                    public void onPosBtnClick() {

                        //取消
                        int orderId = Integer.valueOf(orderInfos.get(position).getO_id());
                        quXiaoOrder(orderId, position);
                    }
                });
                simpleDialog.show();
            }

            @Override
            public void OnPayClickListener(FragmentAllAdapter adapter, int position, String money, View view) {
                //待付款  订单号  总价
//                startActivity(PayActivity.createIntent(getContext(), Base64Util.encodedString("UNO" + orderInfos.get(position).getOrder_no() + "HACHA"), money, "2"));
            }

            @Override
            public void OnSureClickListener(FragmentAllAdapter adapter, final int position, View view) {
                simpleDialog = new SimpleDialog(activity, "已收到商品", "暂未", "确定", new SimpleDialog.OnButtonClick() {
                    @Override
                    public void onNegBtnClick() {
                        simpleDialog.cancel();
                    }

                    @Override
                    public void onPosBtnClick() {
                        //确认收货
                        int orderId = Integer.valueOf(orderInfos.get(position).getO_id());
                        sureOrder(orderId, position);
                    }
                });
                simpleDialog.show();
            }

            @Override
            public void OnDeleteClickListener(FragmentAllAdapter adapter, final int position, View view) {
                simpleDialog = new SimpleDialog(getContext(), "是否删除该订单?", "再想想", "确定", new SimpleDialog.OnButtonClick() {
                    @Override
                    public void onNegBtnClick() {
                        simpleDialog.cancel();
                    }

                    @Override
                    public void onPosBtnClick() {

                        //删除
                        int orderId = Integer.valueOf(orderInfos.get(position).getO_id());
                        deleteOrder(orderId, position);
                    }
                });
                simpleDialog.show();
            }

            @Override
            public void OnPingJiaClickListener(FragmentAllAdapter adapter, int position, View view) {
                //评价
                Intent intent = new Intent(activity, EvaluateActivity.class);
                intent.putExtra("orderId", orderInfos.get(position).getO_id());
                startActivityForResult(intent, REQUEST_EVALUATE);
            }

            @Override
            public void OnRemindClickListener(FragmentAllAdapter adapter, int position, View view) {
                //提醒发货
                int orderId = Integer.valueOf(orderInfos.get(position).getO_id());
                remindOrder(orderId, position);
            }

            @Override
            public void OnLogisticsClickListener(FragmentAllAdapter adapter, int position, View view) {
                //查看物流
                int orderId = Integer.valueOf(orderInfos.get(position).getO_id());
                startActivity(LogisticsActivity.createIntent(activity, "" + orderId,""));
            }

            @Override
            public void OnDrawbackClickListener(FragmentAllAdapter adapter, final int position, View view) {
                simpleDialog = new SimpleDialog(getContext(), "确定申请退款?", "再想想", "确定", new SimpleDialog.OnButtonClick() {
                    @Override
                    public void onNegBtnClick() {
                        simpleDialog.cancel();
                    }

                    @Override
                    public void onPosBtnClick() {

                        //申請退款
                        int orderId = Integer.valueOf(orderInfos.get(position).getO_id());
                        drawBack("" + orderId);
                    }
                });
                simpleDialog.show();
            }
        });
    }

    //申請退款
    private void drawBack(String orderId) {
        SharedPreferences sp = getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        String token = sp.getString("token", "");
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("orderId", orderId);

        XUtil.Post(Url.ORDER_REFUNDORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtils.e("===申请退款==", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.optString("re").equals("1")) {
                        fragmentAllAdapter.loadDataFirstTime();
                    }
                    ToastUtils.showToast(getContext(), jsonObject.optString("info"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });
    }

    //提醒发货
    private void remindOrder(int orderId, final int position) {
        SharedPreferences sp = getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        String token = sp.getString("token", "");
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("orderId", orderId);

        XUtil.Post(Url.ORDER_REMINDSHIPMENT, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.optString("re").equals("1")) {
                        fragmentAllAdapter.removeItem(position);
                        if (position == 0) {
                            fragmentAllAdapter.loadDataFirstTime();
                        }
                    }
                    ToastUtils.showToast(getContext(), jsonObject.optString("info"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });
    }

    /**
     * 删除订单
     *
     * @param orderId
     * @param position
     */
    private void deleteOrder(int orderId, final int position) {
        SharedPreferences sp = getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        String token = sp.getString("token", "");
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("orderId", orderId);

        XUtil.Post(Url.ORDER_DELORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);

                    if ("1".equals(jsonObject.optString("re"))) {
                        fragmentAllAdapter.removeItem(position);
                        if (position == 0) {
                            fragmentAllAdapter.loadDataFirstTime();
                        }
                    }
                    ToastUtils.showToast(getContext(), jsonObject.optString("info"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });

    }

    /**
     * 取消订单
     *
     * @param orderId
     * @param position
     */
    private void quXiaoOrder(int orderId, final int position) {

        SharedPreferences sp = getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        String token = sp.getString("token", "");
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("orderId", orderId);  //代付款

        XUtil.Post(Url.ORDER_CANCELORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    LogUtils.e("===============", "===========" + result);

                    if ("1".equals(jsonObject.optString("re"))) {
                        fragmentAllAdapter.removeItem(position);
                        if (position == 0) {
                            fragmentAllAdapter.loadDataFirstTime();
                        }
                    }
                    ToastUtils.showToast(getContext(), jsonObject.optString("info"));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });

    }

    /**
     * 确认收货
     *
     * @param orderId
     * @param position
     */
    private void sureOrder(int orderId, final int position) {

        SharedPreferences sp = getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        String token = sp.getString("token", "");
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("orderId", orderId);

        XUtil.Post(Url.ORDER_CONFIRMORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);

                    if ("1".equals(jsonObject.optString("re"))) {
                        fragmentAllAdapter.removeItem(position);
                        if (position == 0) {
                            fragmentAllAdapter.loadDataFirstTime();
                        }
                    }
                    ToastUtils.showToast(getContext(), jsonObject.optString("info"));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_EVALUATE)
            if (resultCode == RESULT_OK) {
                //处理扫描结果（在界面上显示）
                if (null != data) {
                    fragmentAllAdapter.loadDataFirstTime();
                }
                super.onActivityResult(requestCode, resultCode, data);
            }
    }

    @Override
    public void loadDataFinished(int datasLength) {
        if (datasLength == 0) {
            layEmtpy.setVisibility(View.VISIBLE);
            tv_msg.setText("暂无订单~");
            recyclerView.setVisibility(View.GONE);
        } else {
            layEmtpy.setVisibility(View.GONE);
        }
    }

}